﻿using Autofac;

namespace DDD.Core.DependencyInjection
{
    public class AutofacIOC : Module, IDisposable
    {
        private static ILifetimeScope _lifetimeScope = null;

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterBuildCallback(liftScope => { _lifetimeScope = liftScope.BeginLifetimeScope(); });

            base.Load(builder);
        }

        public static T Resolve<T>()
            where T : class
        {
            return _lifetimeScope.Resolve<T>();
        }

        public static T KeyResolve<T>(string key)
            where T : class
        {
            return _lifetimeScope.ResolveNamed<T>(key);
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            _lifetimeScope?.Dispose();
            _lifetimeScope = null;
        }
    }
}
